/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bestco.bela.demo;

import com.bestco.bela.EntityClasses.Creditlevel;
import com.bestco.bela.demo.exceptions.IllegalOrphanException;
import com.bestco.bela.demo.exceptions.NonexistentEntityException;
import com.bestco.bela.demo.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import com.bestco.bela.EntityClasses.Login;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author bash
 */
public class CreditlevelJpaController {

    public CreditlevelJpaController() {
        emf = Persistence.createEntityManagerFactory("LoginFramworkPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Creditlevel creditlevel) throws PreexistingEntityException, Exception {
        if (creditlevel.getLoginCollection() == null) {
            creditlevel.setLoginCollection(new ArrayList<Login>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Login> attachedLoginCollection = new ArrayList<Login>();
            for (Login loginCollectionLoginToAttach : creditlevel.getLoginCollection()) {
                loginCollectionLoginToAttach = em.getReference(loginCollectionLoginToAttach.getClass(), loginCollectionLoginToAttach.getUsername());
                attachedLoginCollection.add(loginCollectionLoginToAttach);
            }
            creditlevel.setLoginCollection(attachedLoginCollection);
            em.persist(creditlevel);
            for (Login loginCollectionLogin : creditlevel.getLoginCollection()) {
                Creditlevel oldIdCreditOfLoginCollectionLogin = loginCollectionLogin.getIdCredit();
                loginCollectionLogin.setIdCredit(creditlevel);
                loginCollectionLogin = em.merge(loginCollectionLogin);
                if (oldIdCreditOfLoginCollectionLogin != null) {
                    oldIdCreditOfLoginCollectionLogin.getLoginCollection().remove(loginCollectionLogin);
                    oldIdCreditOfLoginCollectionLogin = em.merge(oldIdCreditOfLoginCollectionLogin);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCreditlevel(creditlevel.getIdCredit()) != null) {
                throw new PreexistingEntityException("Creditlevel " + creditlevel + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Creditlevel creditlevel) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Creditlevel persistentCreditlevel = em.find(Creditlevel.class, creditlevel.getIdCredit());
            Collection<Login> loginCollectionOld = persistentCreditlevel.getLoginCollection();
            Collection<Login> loginCollectionNew = creditlevel.getLoginCollection();
            List<String> illegalOrphanMessages = null;
            for (Login loginCollectionOldLogin : loginCollectionOld) {
                if (!loginCollectionNew.contains(loginCollectionOldLogin)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Login " + loginCollectionOldLogin + " since its idCredit field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Login> attachedLoginCollectionNew = new ArrayList<Login>();
            for (Login loginCollectionNewLoginToAttach : loginCollectionNew) {
                loginCollectionNewLoginToAttach = em.getReference(loginCollectionNewLoginToAttach.getClass(), loginCollectionNewLoginToAttach.getUsername());
                attachedLoginCollectionNew.add(loginCollectionNewLoginToAttach);
            }
            loginCollectionNew = attachedLoginCollectionNew;
            creditlevel.setLoginCollection(loginCollectionNew);
            creditlevel = em.merge(creditlevel);
            for (Login loginCollectionNewLogin : loginCollectionNew) {
                if (!loginCollectionOld.contains(loginCollectionNewLogin)) {
                    Creditlevel oldIdCreditOfLoginCollectionNewLogin = loginCollectionNewLogin.getIdCredit();
                    loginCollectionNewLogin.setIdCredit(creditlevel);
                    loginCollectionNewLogin = em.merge(loginCollectionNewLogin);
                    if (oldIdCreditOfLoginCollectionNewLogin != null && !oldIdCreditOfLoginCollectionNewLogin.equals(creditlevel)) {
                        oldIdCreditOfLoginCollectionNewLogin.getLoginCollection().remove(loginCollectionNewLogin);
                        oldIdCreditOfLoginCollectionNewLogin = em.merge(oldIdCreditOfLoginCollectionNewLogin);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = creditlevel.getIdCredit();
                if (findCreditlevel(id) == null) {
                    throw new NonexistentEntityException("The creditlevel with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Creditlevel creditlevel;
            try {
                creditlevel = em.getReference(Creditlevel.class, id);
                creditlevel.getIdCredit();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The creditlevel with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Login> loginCollectionOrphanCheck = creditlevel.getLoginCollection();
            for (Login loginCollectionOrphanCheckLogin : loginCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Creditlevel (" + creditlevel + ") cannot be destroyed since the Login " + loginCollectionOrphanCheckLogin + " in its loginCollection field has a non-nullable idCredit field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(creditlevel);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Creditlevel> findCreditlevelEntities() {
        return findCreditlevelEntities(true, -1, -1);
    }

    public List<Creditlevel> findCreditlevelEntities(int maxResults, int firstResult) {
        return findCreditlevelEntities(false, maxResults, firstResult);
    }

    private List<Creditlevel> findCreditlevelEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Creditlevel as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Creditlevel findCreditlevel(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Creditlevel.class, id);
        } finally {
            em.close();
        }
    }

    public int getCreditlevelCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Creditlevel as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
